package socket;


import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class SocketService {
    private static final String TAG = "SocketService";
    private boolean isEnable;
    private final WebConfig webConfig;//配置信息
    private final ExecutorService threadPool;//配置线程池
    private ServerSocket socket = null;
    private String log_Text;
    public SocketService(WebConfig webConfig) {
        this.webConfig = webConfig;
        threadPool = Executors.newCachedThreadPool();
    }

    /*
    * 开启服务
    * */
    public void startServiceAsync(){
        isEnable = true;
        new Thread(new Runnable() {
            @Override
            public void run() {
                doProcSync();
            }
        }).start();
    }

    /*
    * 关闭服务
    * */
    public void stopServiceAsync(){
        if(!isEnable){
            return;
        }
        isEnable = true;
        try{
            socket.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        socket = null;
    }

    private void doProcSync(){
        try{
            InetSocketAddress socketAddress = new InetSocketAddress(webConfig.getPort());
            socket = new ServerSocket();
            socket.bind(socketAddress);
            while (isEnable){
                final Socket remotePeer = socket.accept();
                threadPool.submit(new Runnable() {
                    @Override
                    public void run() {
                        System.out.println("doProcSync---------->"+remotePeer.getRemoteSocketAddress().toString());//获取地址
                        //log_Text = remotePeer.getRemoteSocketAddress()+"";
                     onAcceptRemotePeer(remotePeer);
                    }
                });
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    private void onAcceptRemotePeer(Socket remotePeer) {
        try{
            remotePeer.getOutputStream().write("connected successful".getBytes());//告诉客户端连接成功
            InputStream inputStream = remotePeer.getInputStream();//从Socket 当中获取inputStream
            byte buffer[] = new byte[1024*4];
            int temp = 0;
            while ((temp = inputStream.read(buffer)) != -1){
                //Log.e(TAG,new String(buffer,0,temp,"UTF-8"));
                remotePeer.getOutputStream().write(buffer,0,temp);//把客户端传来的消息发送回去
                this.log_Text = new String(buffer,0,temp,"UTF-8");
                System.out.println(getLog_Text());//获取到收到的信息
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public String getLog_Text() {
        return log_Text;
    }
}
